package com.agileai.em.service.expenses;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import net.sf.ehcache.pool.Size;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.em.common.ProcessHelper;
import com.agileai.em.cxmodule.BizCodeUtil;
import com.agileai.em.cxmodule.EmExpReimbursementManage;
import com.agileai.em.wsproxy.ActivityItem;
import com.agileai.em.wsproxy.BizAttribute;
import com.agileai.em.wsproxy.DraftWorkItem;
import com.agileai.em.wsproxy.LaunchWorkItem;
import com.agileai.em.wsproxy.ProcessProfile;
import com.agileai.em.wsproxy.ProcessService;
import com.agileai.em.wsproxy.WorkItem;
import com.agileai.hotweb.controller.core.BaseHandler.OperaType;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.ws.BaseRestService;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

public class DailyReiDataProviderImpl extends BaseRestService implements DailyReiDataProvider{
    
	private static String FAIL = "fail";
	private static String SUCCESS = "success";
	private static String AUDITING = "AUDITING";
	private static String UNSUBMITTED = "UNSUBMITTED";
	public static final String PROCESS_CODE = "Expreimbursement";
	
	@Override
	public String retrieveDailyReiList() {
		
		String responseText = FAIL;
		DataParam param = new DataParam();
		try {
			EmExpReimbursementManage emExpReimbursementManage = this.lookupService(EmExpReimbursementManage.class);
			User user = (User) this.getUser();
			param.put("ER_PERSON",user.getUserId());
			List<DataRow> records = emExpReimbursementManage.findRecords(param);
			JSONArray jsonArray = new JSONArray();
			for(int i=0;i<records.size();i++){
				JSONObject jsonObject = new JSONObject();
				DataRow row = records.get(i);
				String id = row.getString("ER_ID");
				String theme = row.getString("ER_TITLE");
				String submitterName = row.getString("ER_PERSON_NAME");
				Date erDate = (Date) row.get("ER_DATE");
				String commitTime = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_SLANTING, erDate);
				String state = row.getString("ER_STATE");
				String checkStateName = row.getString("ER_STATE_TEXT");
				String money = row.stringValue("ER_MONEY");
				String type = row.stringValue("ER_STYLE_TEXT");
				
				ProcessHelper processHelper = ProcessHelper.instance();
			    ProcessService bpmService = processHelper.getBPMService();
			    WorkItem workItem = this.getActivityName(bpmService, id);
			    
			    String activityName = "";
			    if(workItem != null){
					/*String laucherName = workItem.getLaucherName();
					String laucheTime = workItem.getLaucheTime();*/
					activityName = workItem.getActivityName();
				}
				
				jsonObject.put("id", id);
				jsonObject.put("theme", theme);
				jsonObject.put("submitterName", submitterName);
				jsonObject.put("commitTime", commitTime);
				jsonObject.put("state", state);
				jsonObject.put("checkStateName", checkStateName);
				jsonObject.put("money", money);
				jsonObject.put("type", type);
				jsonObject.put("commitType", checkStateName);
				jsonObject.put("checkNodeName", activityName);
				jsonArray.put(jsonObject);
			}
			responseText = jsonArray.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		
		return responseText;
	}
	
	@Override
	public String retrieveDailyReiDetail( String id) {
		String responseText = FAIL;
		DataParam param = new DataParam();
		try {
			EmExpReimbursementManage emExpReimbursementManage = this.lookupService(EmExpReimbursementManage.class);
			User user = (User) this.getUser();
			param.put("ER_PERSON",user.getUserId());
			param.put("ER_ID",id);
			DataRow record = emExpReimbursementManage.getRecord(param);
			JSONObject jsonObject = new JSONObject();
			String title = record.getString("ER_TITLE");
			String name = record.getString("ER_PERSON_NAME");
			Date erDate = (Date) record.get("ER_DATE");
			String date = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_SLANTING, erDate);
			BigDecimal money = (BigDecimal) record.get("ER_MONEY");
			String style = record.getString("ER_STYLE");
			String remark = record.getString("ER_REMARKS");
			if(StringUtil.isNullOrEmpty(remark)){
				remark = "无";
			}
			JSONArray selectJsonArr = this.getSelectList("ER_STYLE",style);
			
			String state = record.getString("ER_STATE");
			String stateText = record.getString("ER_STATE_TEXT");
			jsonObject.put("id", id);
			jsonObject.put("theme", title);
			jsonObject.put("name", name);
			jsonObject.put("date", date);
			jsonObject.put("money", money);
			jsonObject.put("style", style);
			jsonObject.put("desc", remark);
			jsonObject.put("state", state);
			jsonObject.put("commitType", stateText);
			jsonObject.put("styleSelect", selectJsonArr);
			List<DataRow> records = emExpReimbursementManage.findApproveOpinionRecords(param);
			JSONArray jsonArray = new JSONArray();
			for(int i=0;i<records.size();i++){
				JSONObject jsonObject1 = new JSONObject();
				DataRow row = records.get(i);
				jsonObject1.put("appName", row.getString("EXP_APP_PERSON_NAME"));
				jsonObject1.put("appResult", row.getString("EXP_APP_RESULT_NAME"));
				jsonObject1.put("appDate", row.get("EXP_APP_TIME"));
				String appOpinion = row.getString("EXP_APP_OPINION");
				if(StringUtil.isNullOrEmpty(appOpinion)){
					appOpinion = "无";
				}
				jsonObject1.put("appOpinion",appOpinion);
				jsonArray.put(jsonObject1);
			}
			jsonObject.put("appList", jsonArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return responseText;
	}
	
	@Override
	public String getSelectList(String typeId) {
		String result = "";
		try {
			result  =this.getSelectList(typeId,"").toString();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@Override
	public String saveDetailInfo(DataParam detailInfoParam) {
		String responseText = FAIL;
		
		User user = (User) this.getUser();
		EmExpReimbursementManage emExpReimbursementManage = this.lookupService(EmExpReimbursementManage.class);
		String operationType = detailInfoParam.stringValue("operationType");
		DataParam param = new DataParam();
		param.put("ER_PERSON",user.getUserId());
		param.put("ER_STYLE", detailInfoParam.stringValue("style"));
		param.put("ER_TITLE", detailInfoParam.stringValue("theme"));
		param.put("ER_MONEY", detailInfoParam.stringValue("money"));
		param.put("ER_REMARKS", detailInfoParam.stringValue("desc"));
		param.put("ER_STATE", "UNSUBMITTED");
		param.put("ER_DATE", new Date());
		
		if (OperaType.CREATE.equals(operationType)){
			param.put("sdate",DateUtil.getDateByType(DateUtil.YYMMDD_SLANTING, new Date())+" 00:00:00");
			param.put("edate",DateUtil.getDateByType(DateUtil.YYMMDD_SLANTING, new Date())+" 23:59:59");
			List<DataRow> list = emExpReimbursementManage.findRecords(param);
			String bizCode = BizCodeUtil.create("ER", list, BizCodeUtil.withPrefix);
			param.put("ER_CODE",bizCode);
			emExpReimbursementManage.createRecord(param);
			ProcessHelper processHelper = ProcessHelper.instance();
	   		ProcessService processService = processHelper.getBPMService();
	   		String uuId = param.get("ER_ID");
	   		DraftWorkItem draftWorkItem = new DraftWorkItem();
	   		draftWorkItem.setProcessCode(PROCESS_CODE);
	   		draftWorkItem.setUserCode(user.getUserCode());
	   		draftWorkItem.setBizTitle(param.getString("ER_TITLE"));
	   		draftWorkItem.setBizRecordId(uuId);
	   		draftWorkItem.setBizRecordCode(param.getString("ER_CODE"));
	   		processService.saveDraft(draftWorkItem);
	   		responseText = SUCCESS;	
		}else if ("edit".equals(operationType)){
			BigDecimal money = new BigDecimal(detailInfoParam.stringValue("money"));
			String strDate = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL, new Date());
			Date date = DateUtil.getDate(strDate);
			String state = UNSUBMITTED;
			param.put("ER_ID",detailInfoParam.stringValue("id"));
			param.put("ER_DATE",date);
			param.put("ER_STATE", state);
			
			emExpReimbursementManage.updateRecord(param);
			responseText = SUCCESS;	
		}
		
		return responseText;
	}
	
	@Override
	public String submitDetailInfo(DataParam detailInfoParam) {
		String responseText = FAIL;
		User user = (User) this.getUser();
		DataParam param = new DataParam();
		param.put("ER_PERSON",user.getUserId());
		param.put("ER_STYLE", detailInfoParam.stringValue("style"));
		param.put("ER_TITLE", detailInfoParam.stringValue("theme"));
		param.put("ER_MONEY", detailInfoParam.stringValue("money"));
		param.put("ER_REMARKS", detailInfoParam.stringValue("desc"));
		param.put("ER_STATE", "UNSUBMITTED");
		try {
			EmExpReimbursementManage mobileManage = this.lookupService(EmExpReimbursementManage.class);
			String ER_ID = detailInfoParam.getString("id");
			String ER_STATE = AUDITING; 
			param.put("ER_ID", ER_ID,"ER_STATE",ER_STATE);
			mobileManage.changeStateRecord(param);
			
			DataRow row = mobileManage.getRecord(param);
			List<BizAttribute> attributeList = new ArrayList<BizAttribute>();
	   		BizAttribute bizAttribute = new BizAttribute();
	   		bizAttribute.setCode("userId");
	   		bizAttribute.setValue(user.getUserId());
	   		attributeList.add(bizAttribute);
	   		String bizRecordId = ER_ID;
	   		if(StringUtil.isNullOrEmpty(bizRecordId)){
	   			bizRecordId = KeyGenerator.instance().genKey();
	   		}
	   		ProcessHelper processHelper = ProcessHelper.instance();
	   		ProcessService processService = processHelper.getBPMService();
	   		String processId = processService.getCurrentProcessId(PROCESS_CODE);
	   		String title = row.getString("ER_TITLE");
	   		LaunchWorkItem launchWorkItem = processHelper.createLaunchWorkItem(processId);
	   		launchWorkItem.getAttributeList().addAll(attributeList);
	   		launchWorkItem.setTitle(title);
	   		launchWorkItem.setBizRecordId(bizRecordId);
	   		launchWorkItem.setUserCode(user.getUserCode());
	   		param.put("SKIP_FIRST_NODE", "true");
	   		boolean skipFirstNode = "true".equals(param.get("SKIP_FIRST_NODE"));
	   		processService.launchProcess(launchWorkItem,skipFirstNode);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return responseText;
	}
	
	@Override
	public String retrieveDailyReiDetailTast(String id) {
		String responseText = FAIL;
		DataParam param = new DataParam();
		try {
			EmExpReimbursementManage emExpReimbursementManage = this.lookupService(EmExpReimbursementManage.class);
			User user = (User) this.getUser();
			param.put("ER_PERSON",user.getUserId());
			param.put("ER_ID",id);
			DataRow record = emExpReimbursementManage.getRecord(param);
			JSONObject jsonObject = new JSONObject();
			String title = record.getString("ER_TITLE");
			String name = record.getString("ER_PERSON_NAME");
			Date erDate = (Date) record.get("ER_DATE");
			String date = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_SLANTING, erDate);
			BigDecimal money = (BigDecimal) record.get("ER_MONEY");
			String style = record.getString("ER_STYLE");
			String styleText = record.getString("ER_STYLE_TEXT");
			String remark = record.getString("ER_REMARKS");
			if(StringUtil.isNullOrEmpty(remark)){
				remark = "无";
			}
			
			ProcessHelper processHelper = ProcessHelper.instance();
		    ProcessService bpmService = processHelper.getBPMService();
		    WorkItem workItem = this.getActivityName(bpmService, id);
		    String activityName = "";
		    if(workItem != null){
				/*String laucherName = workItem.getLaucherName();
				String laucheTime = workItem.getLaucheTime();*/
				activityName = workItem.getActivityName();
			}
			
			String state = record.getString("ER_STATE");
			String stateText = record.getString("ER_STATE_TEXT");
			jsonObject.put("id", id);
			jsonObject.put("theme", title);
			jsonObject.put("name", name);
			jsonObject.put("date", date);
			jsonObject.put("money", money);
			jsonObject.put("style", styleText);
			jsonObject.put("desc", remark);
			jsonObject.put("state", state);
			jsonObject.put("commitType", stateText);
			jsonObject.put("checkNodeName", activityName);
			
			JSONArray jsonArray = this.getAppListArr("Expreimbursement", id);
			jsonObject.put("appList", jsonArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		
		return responseText;
	}
	
	private WorkItem getActivityName(ProcessService bpmService,String id){
		WorkItem workItem = null;
		List<WorkItem> taskItemList = bpmService.findWorkItems("");
		String a =taskItemList.toString();
		for (int i = 0; i < taskItemList.size(); i++) {
			WorkItem taskItem = taskItemList.get(i);
			String bizId = taskItem.getBusinessId();
			
			if(bizId.equals(id)){
				workItem =  taskItem;
			}
		}
		return workItem;
	}
	
	private JSONArray getSelectList(String TypeId,String selectedId) throws JSONException{
		EmExpReimbursementManage emExpReimbursementManage = this.lookupService(EmExpReimbursementManage.class);
		List<DataRow> list = emExpReimbursementManage.getSelectList(TypeId);
		
		DataRow emptyItemRow = new DataRow();
		emptyItemRow.put("code", "");
		emptyItemRow.put("name", "请选择");
		list.add(0, emptyItemRow);
		
		JSONArray jsonArr = new JSONArray();
		for(int i = 0;i < list.size(); i++){
			DataRow row = list.get(i);
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("code", row.stringValue("code"));
			jsonObj.put("name", row.stringValue("name"));
			if(selectedId.equals(row.stringValue("code"))){
				jsonObj.put("selected", true);
			}else{
				jsonObj.put("selected", false);
			}
			
			jsonArr.put(jsonObj);
		}
		
		return jsonArr;
	}
	
	private JSONArray getAppListArr(String processCode,String bussinessId ) throws JSONException{
		JSONArray arr = new JSONArray();
		DataParam param = new DataParam();
		param.put("ER_ID",bussinessId);
		ProcessHelper processHelper = ProcessHelper.instance();
		ProcessService bpmService = processHelper.getBPMService();
		EmExpReimbursementManage emExpReimbursementManage = this.lookupService(EmExpReimbursementManage.class);
		
		ProcessProfile processProfile = bpmService.loadProcessProfile(processCode, bussinessId);
		HashMap<String, DataRow> records = emExpReimbursementManage.findApproveMobilityRecords(param);
		List<ActivityItem> processList = processProfile.getActivityItems();
	    Collections.sort(processList, new Comparator<ActivityItem>() {
			@Override
			public int compare(ActivityItem a, ActivityItem b) {
				String timeA = a.getOperatorTime();
				String timeB = b.getOperatorTime();
				if(StringUtil.isNullOrEmpty(timeA)||StringUtil.isNullOrEmpty(timeB)){
					return 0;
				}
				return timeA.compareTo(timeB);
			}  
		 });
		
	    int processListSize = processList.size();
	    Collections.reverse(processList);
		
		for(int i=0;i<processListSize;i++){
			ActivityItem activityItem = processList.get(i);
			DataRow row = new DataRow();
			String activityInstId = activityItem.getActivityInstId();
			String activityInstType = activityItem.getItemType();
			String appName = activityItem.getOperatorName();
			String appDate = activityItem.getOperatorTime();
			String actName = activityItem.getActivityName();
			String appResult = activityItem.getActivityName();
			String imgUrl = "pass.png";
			String imgBg = "#75ce66";
			if("instance".equals(activityInstType)){
				imgUrl = "wait.png";
				imgBg = "#ffdf00";
			}
			
			if(StringUtil.isNullOrEmpty(appName)){
				appName =actName;
			}
			
			String appOpinion = "";
			if(records.containsKey(activityInstId)){
				row = records.get(activityInstId);
				appResult = row.getString("EXP_APP_RESULT_NAME");
				appOpinion = row.getString("EXP_APP_OPINION");
			}
			
			JSONObject jsonObject1 = new JSONObject();
			jsonObject1.put("appName", appName);
			jsonObject1.put("appResult", appResult);
			jsonObject1.put("appDate", appDate);
			jsonObject1.put("appOpinion",appOpinion);
			jsonObject1.put("imgUrl",imgUrl);
			jsonObject1.put("imgBg",imgBg);
			if(!actName.equals("开始")&&!actName.equals("结束")){
				arr.put(jsonObject1);
			}
		}
		return arr;
	}
	

}
